package com.liukuo.uitl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: liukuo
 * Date: 12-7-1                                                                      s
 * Time: 下午6:47
 * To change this template use File | Settings | File Templates.
 */
public class AccessClient {
    public static String doRequest(String urlString, String name,String password,HashMap<String,String> params) throws Exception{
        try {
            URL url = new URL(urlString);

            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            connection.setRequestProperty("Authorization", "Basic " + name +":"+ password);
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            if (params != null && !params.isEmpty()) {
                StringBuffer buf = new StringBuffer();
                for(String key : params.keySet()){
                    buf.append("&").append(key).append("=").append(params.get(key));
                }
                buf.deleteCharAt(0);
                connection.getOutputStream().write(buf.toString().getBytes("UTF-8"));
                connection.getOutputStream().close();
            }
            InputStream inputStream = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            String line = br.readLine();
            br.close();
            return line.trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String doRequest(String urlString, String name,String password) throws Exception{
        return doRequest(urlString,name,password,null);
    }
}
